package com.btl.fragment;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.http.Header;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.btl.bean.Person;
import com.btl.cygf.FaBuActivity;
import com.btl.cygf.FaTie;
import com.btl.cygf.MainActivity;
import com.btl.cygf.MyFriendActivity;
import com.btl.cygf.PersonInfo;
import com.btl.cygf.PingLunActivity;
import com.btl.cygf.R;
import com.btl.cygf.RecordActivity;
import com.btl.cygf.SheZhiActivity;
import com.btl.cygf.ShouCangActivity;
import com.btl.fragment.ShequFragment.myPagerAdapter;
import com.btl.http.HttpServies;
import com.btl.utils.RoundImag;
import com.btl.utils.SavaPersonInfo;
import com.btl.zujian.SelectPicPopup;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.yzx.yunyanzhengdemo.activity.LoginActivity;

public class WoFragment extends Fragment {

	private TextView Registration_OK;
	private TextView nickname;
	private TextView qianming,wo_guanzhu_person;
	private ImageView My_head;
	private SelectPicPopup spp;
	
	private TextView wo_history;
	
	SharedPreferences share;

	private static String path = "/sdcard/btl/";// sd路径
	private Bitmap head;

	private Bitmap pic;

	// linearlayout布局
	private LinearLayout My_list_myrelease, My_list_collection,
			My_list_message, My_list_record, My_list_youlove, My_list_myfriend,
			My_list_shezhi, login_success,My_list_fatie;

	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			if (msg.what == 0x1123) {
				if(pic == null) {
					My_head.setImageResource(R.drawable.bad_face_lib);
				} else {
					
					if(!(pic == null)) {
						My_head.setImageBitmap(RoundImag.toRoundBitmap(getActivity()
								.getApplicationContext(), pic));
					}
					
					
				}
			}

		}

	};

	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View messageLayout = inflater.inflate(R.layout.wo_layout, container,
				false);
		nickname = (TextView) messageLayout.findViewById(R.id.nickname);
		My_head = (ImageView) messageLayout.findViewById(R.id.My_head);
		qianming = (TextView) messageLayout.findViewById(R.id.qianming);
		Registration_OK = (TextView) messageLayout
				.findViewById(R.id.Registration_OK);
		My_list_myrelease = (LinearLayout) messageLayout
				.findViewById(R.id.My_list_myrelease);
		login_success = (LinearLayout) messageLayout
				.findViewById(R.id.login_success);
		My_list_collection = (LinearLayout) messageLayout
				.findViewById(R.id.My_list_collection);
		My_list_message = (LinearLayout) messageLayout
				.findViewById(R.id.My_list_message);
		My_list_record = (LinearLayout) messageLayout
				.findViewById(R.id.My_list_record);
		
		My_list_myfriend = (LinearLayout) messageLayout
				.findViewById(R.id.My_list_myfriend);
		My_list_shezhi = (LinearLayout) messageLayout
				.findViewById(R.id.My_list_shezhi);
		My_list_fatie = (LinearLayout) messageLayout
				.findViewById(R.id.My_list_fatie);
		
		wo_history =(TextView) messageLayout.findViewById(R.id.wo_history);
		wo_guanzhu_person =(TextView) messageLayout.findViewById(R.id.wo_guanzhu_person);
		

		MyOnclickListener myOnclickListener = new MyOnclickListener();

		wo_guanzhu_person.setOnClickListener(myOnclickListener);
		wo_history.setOnClickListener(myOnclickListener);
		Registration_OK.setOnClickListener(myOnclickListener);
		My_list_myrelease.setOnClickListener(myOnclickListener);
		My_list_collection.setOnClickListener(myOnclickListener);
		My_list_message.setOnClickListener(myOnclickListener);
		My_list_record.setOnClickListener(myOnclickListener);
		My_list_myfriend.setOnClickListener(myOnclickListener);
		My_list_shezhi.setOnClickListener(myOnclickListener);
		My_head.setOnClickListener(myOnclickListener);
		login_success.setOnClickListener(myOnclickListener);
		My_list_fatie.setOnClickListener(myOnclickListener);

		return messageLayout;
	}

	@Override
	public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		initView(view);
	}

	private void initView(View view) {
		nickname = (TextView) view.findViewById(R.id.nickname);
		qianming = (TextView) view.findViewById(R.id.qianming);
		My_head = (ImageView) view.findViewById(R.id.My_head);
		Registration_OK = (TextView) view.findViewById(R.id.Registration_OK);
		My_list_myrelease = (LinearLayout) view
				.findViewById(R.id.My_list_myrelease);
		login_success = (LinearLayout) view.findViewById(R.id.login_success);
		My_list_collection = (LinearLayout) view
				.findViewById(R.id.My_list_collection);
		My_list_message = (LinearLayout) view
				.findViewById(R.id.My_list_message);
		My_list_record = (LinearLayout) view.findViewById(R.id.My_list_record);
		
		My_list_myfriend = (LinearLayout) view
				.findViewById(R.id.My_list_myfriend);
		My_list_shezhi = (LinearLayout) view.findViewById(R.id.My_list_shezhi);
		My_list_fatie = (LinearLayout) view.findViewById(R.id.My_list_fatie);
		
		wo_history =(TextView) view.findViewById(R.id.wo_history);
		wo_guanzhu_person =(TextView) view.findViewById(R.id.wo_guanzhu_person);

		MyOnclickListener myOnclickListener = new MyOnclickListener();
		
		wo_history.setOnClickListener(myOnclickListener);

		wo_guanzhu_person.setOnClickListener(myOnclickListener);
		Registration_OK.setOnClickListener(myOnclickListener);
		My_list_myrelease.setOnClickListener(myOnclickListener);
		My_list_collection.setOnClickListener(myOnclickListener);
		My_list_message.setOnClickListener(myOnclickListener);
		My_list_record.setOnClickListener(myOnclickListener);
		My_list_myfriend.setOnClickListener(myOnclickListener);
		My_list_shezhi.setOnClickListener(myOnclickListener);
		My_head.setOnClickListener(myOnclickListener);
		login_success.setOnClickListener(myOnclickListener);
		My_list_fatie.setOnClickListener(myOnclickListener);

		// Registration_OK.setVisibility(View.GONE);
		share = getActivity().getSharedPreferences("login",
				Activity.MODE_WORLD_READABLE);

		String id = share.getString("id", "");
		if (!id.equals("")) {
			String zhuangtai = share.getString("zhuangtai", "");
			if (!zhuangtai.equals("1")) {
				Toast.makeText(getActivity().getApplicationContext(),
						"此账号已被限制", 1).show();
				SavaPersonInfo.saveInfo(getActivity(), new Person());

				Intent it = new Intent();
				it.setClass(getActivity(), MainActivity.class);
				it.putExtra("type", 1);
				it.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(it);
			} else {
				Registration_OK.setVisibility(View.GONE);
				String name = share.getString("nickname", "");
				if (name.equals("")) {
					nickname.setText(id);
				} else {
					nickname.setText(name);
				}
				String intro = share.getString("intro", "");
				if (intro.equals("")) {
					qianming.setText("这个人很懒什么都没有留下 ！");
				} else {
					qianming.setText(intro);
				}

				final String avatar = share.getString("avatar", "");

				if (!avatar.equals("")) {
					new Thread(new Runnable() {
						@Override
						public void run() {

							try {
								pic = HttpServies.getBitmap(avatar);
							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							handler.sendEmptyMessage(0x1123);
						}
					}).start();

				}

				login_success.setVisibility(View.VISIBLE);
			}

		}

	}

	private void getImage() {

		spp = new SelectPicPopup(getActivity(), itemsOnClick);
		spp.showAtLocation(getActivity().findViewById(R.id.main),
				Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);

	}

	private OnClickListener itemsOnClick = new OnClickListener() {

		public void onClick(View v) {
			spp.dismiss();
			switch (v.getId()) {
			case R.id.btn_take_photo://拍照
				Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				intent2.putExtra(MediaStore.EXTRA_OUTPUT, Uri
						.fromFile(new File(Environment
								.getExternalStorageDirectory(), "head.jpg")));
				startActivityForResult(intent2, 2);// 采用ForResult打开
				
				break;
			case R.id.btn_pick_photo://选取相册
				Intent intent1 = new Intent(Intent.ACTION_PICK, null);
				intent1.setDataAndType(
						MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
				startActivityForResult(intent1, 1);
				
				break;
			default:
				break;
			}

		}

	};
	
	private void saveAvatar() {
		SharedPreferences share = getActivity().getSharedPreferences("login",
				Activity.MODE_WORLD_READABLE);

		String id = share.getString("id", "");
		AsyncHttpClient client = new AsyncHttpClient();
		RequestParams params = new RequestParams();
		params.put("id", id);
		try {
			params.put("image", new File(path + "head.jpg"));
			client.post("http://10.202.1.42:8080/CYGF/updateAvatar.user",params,
					new AsyncHttpResponseHandler() {
						
						@Override
						public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
							Toast.makeText(getActivity(), "修改成功", 1).show();
							My_head.setImageBitmap(RoundImag.toRoundBitmap(getActivity()
									.getApplicationContext(), BitmapFactory.decodeFile(path + "head.jpg")));
							
							
						}
						
						@Override
						public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
							Toast.makeText(getActivity(), "修改失败", 1).show();
							
						}
					});
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	public class MyOnclickListener implements View.OnClickListener {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			
			
			case R.id.Registration_OK:
				// 点击登录/注册按钮
				Intent intent = new Intent();
				intent.putExtra("type", "2");
				intent.setClass(getActivity(), LoginActivity.class);
				startActivity(intent);
				break;
			case R.id.My_list_shezhi: //点击设置
				
				startActivity(new Intent(getActivity(), SheZhiActivity.class));
				break;
			case R.id.My_head://点击头像
				SharedPreferences share = getActivity().getSharedPreferences("login",
						Activity.MODE_WORLD_READABLE);

				String id = share.getString("id", "");
				if (!id.equals("")) {
					getImage();
				}
				break;
			case R.id.login_success://点击昵称和签名
				startActivity(new Intent(getActivity(), PersonInfo.class));
				break;
			case R.id.My_list_fatie://点击发帖
				SharedPreferences share1 = getActivity().getSharedPreferences("login",
						Activity.MODE_WORLD_READABLE);

				String pid = share1.getString("id", "");
				if (!pid.equals("")) {
					startActivity(new Intent(getActivity(), FaTie.class));
				} else {
					Intent it2 = new Intent();
					it2.putExtra("type", "2");
					it2.setClass(getActivity(), LoginActivity.class);
					startActivity(it2);
				}
				
				break;
				
			case R.id.My_list_myrelease://点击我的发布
				SharedPreferences share2 = getActivity().getSharedPreferences("login",
						Activity.MODE_WORLD_READABLE);

				String mid = share2.getString("id", "");
				if (!mid.equals("")) {
					startActivity(new Intent(getActivity(), FaBuActivity.class));
				} else {
					Intent it2 = new Intent();
					it2.putExtra("type", "2");
					it2.setClass(getActivity(), LoginActivity.class);
					startActivity(it2);
				}
				
				break;
				

			case R.id.My_list_collection: // 点击我的收藏
				SharedPreferences share3 = getActivity().getSharedPreferences("login",
						Activity.MODE_WORLD_READABLE);

				String cid = share3.getString("id", "");
				if (!cid.equals("")) {
					startActivity(new Intent(getActivity(), ShouCangActivity.class));
				} else {
					Intent it2 = new Intent();
					it2.putExtra("type", "2");
					it2.setClass(getActivity(), LoginActivity.class);
					startActivity(it2);
				}
				
				break;
			case R.id.My_list_message: //点击我的评论
				SharedPreferences share4= getActivity().getSharedPreferences("login",
						Activity.MODE_WORLD_READABLE);

				String eid = share4.getString("id", "");
				if (!eid.equals("")) {
					startActivity(new Intent(getActivity(), PingLunActivity.class));
				} else {
					Intent it2 = new Intent();
					it2.putExtra("type", "2");
					it2.setClass(getActivity(), LoginActivity.class);
					startActivity(it2);
				}
				break;
				
			case R.id.wo_history://点击历史记录
				
				SharedPreferences share5= getActivity().getSharedPreferences("login"  , Activity.MODE_WORLD_READABLE);
				String zhuanttai = share5.getString("id", "");
				if(!zhuanttai.equals("")){
					Intent inte = new Intent();
					inte.setClass(getActivity(), RecordActivity.class);
					inte.putExtra("id", zhuanttai);
					startActivity(inte);
				}else {
					Intent it2 = new Intent();
					it2.putExtra("type", "2");
					it2.setClass(getActivity(), LoginActivity.class);
					startActivity(it2);
				}

				break;
				
			case R.id.wo_guanzhu_person: //点击关注的人
				SharedPreferences share6= getActivity().getSharedPreferences("login"  , Activity.MODE_WORLD_READABLE);
				String zhuant = share6.getString("id", "");
				if(!zhuant.equals("")){
					Intent inte = new Intent();
					inte.setClass(getActivity(), MyFriendActivity.class);
					inte.putExtra("id", zhuant);
					startActivity(inte);
				}else{
					Intent it2 = new Intent();
					it2.putExtra("type", "2");
					it2.setClass(getActivity(), LoginActivity.class);
					startActivity(it2);
				}

				break;

				
				
			}

		}

	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case 1:
			if (resultCode == -1) {
				cropPhoto(data.getData());// 裁剪图片
			}
			break;
		case 2:
			if (resultCode == -1) {
				File temp = new File(Environment.getExternalStorageDirectory()
						+ "/head.jpg");
				cropPhoto(Uri.fromFile(temp));// 裁剪图片
			}
			break;
		case 3:
			if (data != null) {
				Bundle extras = data.getExtras();
				head = extras.getParcelable("data");
				if (head != null) {
					/**
					 * 上传服务器代码
					 */
					System.out.println(head);
					setPicToView(head);// 保存在SD卡中

				}
			}
			break;
		default:
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	};

	/**
	 * 调用系统的裁剪
	 * 
	 * @param uri
	 */
	public void cropPhoto(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 150);
		intent.putExtra("outputY", 150);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, 3);
	}

	private void setPicToView(Bitmap mBitmap) {
		String sdStatus = Environment.getExternalStorageState();
		if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
			return;
		}
		FileOutputStream b = null;
		File file = new File(path);
		file.mkdirs();// 创建文件夹
		String fileName = path + "head.jpg";// 图片名字
		try {
			b = new FileOutputStream(fileName);
			mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
			saveAvatar();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} finally {
			try {
				// 关闭流
				b.flush();
				b.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
